<?php

namespace Qy\Controller;

use Common\Controller\BaseController;

/**
 * 任务(这里的做任务就是课时的考试)
 * 此类内容可以在用户所在企业失效的情况下访问（我做过的任务）
 */
class TaskController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        empty($this->iUserId) && $this->error("请登录!", -103);
    }

    //所有岗位的专业列表
    public function allSpecialtyList() {
        $post_id = $this->iPostId;
        $specialtyList = M("Specialty")->field("specialty_id,specialty_name,cate_id")->where(array('status' => 1))->order("sort ASC")->select();
        if (empty($specialtyList)) {
            $this->success("没有数据");
        }
        foreach ($specialtyList as $val) {
            $arrSpecialtyList[$val['cate_id']][] = $val;
        }

        if ($this->iRoleId == 1) {   //拥有者
            $list['self_specialty'] = $arrSpecialtyList;
        } else {
            //自己的专业
            $list['self_specialty'] = $arrSpecialtyList[$post_id];
            unset($arrSpecialtyList[$post_id]);
            $list['other_specialty'] = $arrSpecialtyList;
        }

        $this->returnList($list);
    }

    //任务-课程列表
    public function curriculumList() {
        $cate_id = $this->iPostId;
        $specialty_id = M("Specialty")->where(array('cate_id' => $cate_id))->order("sort asc")->limit(1)->getField("specialty_id");
        $specialty_id = I("specialty_id", $specialty_id, "intval"); //默认给获取第一个专业下的课程列表
        $list = M("Curriculum")->field("curriculum_id,curriculum_name,curriculum_img,description,specialty_id")->where(array('specialty_id' => $specialty_id, 'status' => 1))->select();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['curriculum_img'] = C('ADMIN_URL') . $val['curriculum_img'];
            }
            unset($val);
        }
        $this->returnList($list);
    }

    /**
     * 任务-章节列表
     */
    public function chapterList() {
        $curriculum_id = I("curriculum_id", 0, "intval");
        $chapterList = M("Chapter")->field("chapter_id,chapter_name")->where(array('curriculum_id' => $curriculum_id, 'status' => 1))->order("sort ASC")->select();
        if (!empty($chapterList)) {
            $num = 1;
            foreach ($chapterList as &$val) {
                $val['chapter_num'] = '章节' . ToChinaseNum($num++);
            }
        }

        $this->returnList($chapterList);
    }

    /**
     * 任务-课时列表
     * task_type：任务类型 1-随堂任务 2-随堂进阶
     */
    public function periodList() {
        $iTaskType = $this->getParam('task_type', 0, '/^[1|2]$/', TRUE, '参数错误');
        $iChapterId = $this->getParam('chapter_id', 0, 'int+', TRUE);
        $iUserId = $this->iUserId;
        $arrPeriod = M()->table('qy_period p')
                ->field('
                        p.period_id,p.period_name,p.period_img,p.period_desc,
                        IF(MIN(upr.create_time),1,0) as op_status,
                        MAX(pp.total_score) as max_total_score,
                        pp.user_id
                ')
                ->join('LEFT JOIN qy_user_period_record as upr ON upr.period_id = p.period_id AND upr.user_id =' . $iUserId)
                ->join('LEFT JOIN qy_paper AS pp ON pp.relat_id = p.period_id AND pp.type = ' . $iTaskType . ' AND pp.status = 1 AND pp.user_id = ' . $iUserId)
                ->where(array('p.chapter_id' => $iChapterId, 'p.status' => 1))
                ->group('p.period_id')
                ->order('p.sort ASC')
                ->select();
        
        if ($arrPeriod) {
            foreach ($arrPeriod as &$val) {
                $val['period_img'] = C('ADMIN_URL') . $val['period_img'];
                $val['max_total_score'] = format_score($val['max_total_score']);
                $val['star_num'] = $this->_starNum($val['max_total_score']);
            }
        }
        $this->returnList($arrPeriod);
    }

    /**
     * 任务-题目列表
     * task_type：任务类型 1-随堂任务 2-随堂进阶
     */
    public function questionList() {
        $iUserId = $this->iUserId;
        $task_type = I("task_type", 0, "intval");
        if (!in_array($task_type, [1, 2])) {
            $this->error('参数错误');
        }
        $period_id = I("period_id", 0, "intval");
        $objQuestion = M("Question");
        $objPaper = M("Paper");
        //判断该用户在该课时是否有没做完的试卷
        $paperInfo = $objPaper->where(array('user_id'=>$iUserId,'relat_id' => $period_id, 'type' => $task_type, 'status' => 0))->find();
        $now_right_count = 0;  //目前答对题目数
        $now_wrong_count = 0;  //目前答错题目数
        $num = 1; //题目序号
        if (!empty($paperInfo)) {
            $returnList['paper_id'] = $paperInfo['paper_id'];
            $questionList = $objQuestion->field("question_id,title,question_img,addition,score")->where(array('question_id' => array('in', $paperInfo['choice_ids'])))->order("field(question_id," . $paperInfo['choice_ids'] . ")")->select();
            //查询该试卷已经答过题目
            $answerList = M("UserAnswer")->field('question_id,check_score')->where(array('user_id' => $iUserId, 'paper_id' => $paperInfo['paper_id']))->select();
            foreach ($questionList as &$val) {
                $val['num'] = $num++;
                $val['check_score'] = '-1';     //表示该题目还未被作答。 0：答错 大于0：正确 -1：未作答
                foreach ($answerList as $vv) {
                    if ($vv['question_id'] == $val['question_id']) {
                        $val['check_score'] = $vv['check_score'];
                        if ($val['score'] == $vv['check_score']) {
                            $now_right_count++;
                        } else {
                            $now_wrong_count++;
                        }
                    }
                }
                $val['question_img'] = json_decode($val['question_img']);
                if (!empty($val['question_img'])) {
                    foreach ($val['question_img'] as &$img_val) {
                        $img_val = C('ADMIN_URL') . $img_val;
                    }
                    unset($img_val);
                }
                $val['addition'] = json_decode($val['addition']);
            }
            unset($val);
        } else {
            switch ($task_type) {
                case 1:
                    $question_type = 0;     //单选题目
                    break;
                case 2:
                    $question_type = 1;     //多选题目
                    break;
            }
            //1.先生成试卷（选择题打乱随机）
            $arrQueList = $objQuestion->field("question_id")->where(array('relat_id' => $period_id, 'type' => $question_type, 'status' => 1))->select();
            if (empty($arrQueList)) {
                $this->error('没有任务题目');
            }
            foreach ($arrQueList as $val) {
                $qids[] = $val['question_id'];
            }
            shuffle($qids);
            //2.记录这次考试题顺序
            $iCompanyId = $this->iCompanyId;
            $data['user_id'] = $iUserId;
            $data['type'] = $task_type;
            $data['relat_id'] = $period_id;
            $data['company_id'] = empty($iCompanyId) ? 0 : $iCompanyId;
            $data['choice_ids'] = implode(",", $qids);
            $data['create_time'] = date("Y-m-d H:i:s");
            $paper_id = $objPaper->add($data);
            $returnList['paper_id'] = $paper_id;
            
            //3.试题排序成打乱的顺序
            $questionList = $objQuestion->field("question_id,title,question_img,addition,score")->where(array('question_id' => array('in', $qids)))->order("field(question_id," . implode(",", $qids) . ")")->select();
            foreach ($questionList as &$val) {
                $val['num'] = $num++;
                $val['check_score'] = '-1';     //表示该题目还未被作答。 0：打错 大于0：正确 -1：未作答
                $val['question_img'] = json_decode($val['question_img']);
                if (!empty($val['question_img'])) {
                    foreach ($val['question_img'] as &$img_val) {
                        $img_val = C('ADMIN_URL') . $img_val;
                    }
                    unset($img_val);
                }
                $val['addition'] = json_decode($val['addition']);
            }
            unset($val);
        }

        $returnList['question_total'] = count($questionList);
        $returnList['now_right_count'] = $now_right_count;
        $returnList['now_wrong_count'] = $now_wrong_count;
        $returnList['question_list'] = $questionList;
        $this->returnList($returnList);
    }

    //任务-答案验证
    public function answerCheck() {
        $iUserId = $this->iUserId;
        $paper_id = $this->getParam('paper_id', 0, 'int+', TRUE);
        $question_id = $this->getParam('question_id', 0, 'int+', TRUE);
        $s_answer = $this->getParam('s_answer', '', 'string', TRUE);

        $objUserAnswer = M("UserAnswer");
        $is_sub = $objUserAnswer->where(array('paper_id' => $paper_id, 'user_id' => $iUserId, 'question_id' => $question_id))->count(1);
        if (!empty($is_sub)) {
            $this->error('不能重复提交！');
        }

        $questionAll = M("Paper")->field('choice_ids,relat_id,type')->where(array('paper_id' => $paper_id))->find();
        $questionArr = explode(',', $questionAll['choice_ids']);
        $is_exist = in_array($question_id, $questionArr);
        if (empty($is_exist)) {
            $this->error('该题目不存在试卷中！');
        }
        $last_id = $questionArr[count($questionArr) - 1];

        //查找chapter_id
        //$chapter_id = M("Period")->where(array('period_id' => $questionAll["relat_id"]))->getField('chapter_id');

        $questionInfo = M('Question')->field("answer,score")->where(array('question_id' => $question_id))->find();

        if ($questionInfo['answer'] == $s_answer) {//v1.0.5以后版本，0-答错 大于0-答对
            $data['check_score'] = !empty($questionInfo['score']) ? $questionInfo['score'] : 1;  //防止原题目分为0; 
        } else {
            $data['check_score'] = 0;
        }
        $data['s_answer'] = $s_answer;
        $data['paper_id'] = $paper_id;
        $data['user_id'] = $iUserId;
        $data['question_id'] = $question_id;
        $data['create_time'] = date("Y-m-d H:i:s");
        if (!M("UserAnswer")->add($data)) {
            $this->error('操作失败');
        }

        if ($question_id == $last_id) {   //判断是否最后一题，然后打分
            $answerList = $objUserAnswer->field('check_score')->where(array('paper_id' => $paper_id, 'user_id' => $iUserId))->select();
            $right_count = 0;
            foreach ($answerList as $val) {
                if ($val['check_score'] > 0) {
                    $right_count++;
                }
            }
            $question_total = count($answerList);   //因为已经答到最后一题，所以答题总数就是问题总数
            $total_score = round($right_count / $question_total * 100); //【计算总分方式：答对题目/总题目数*100】
            $arrData['total_score'] = $total_score;
            $arrData['paper_id'] = $paper_id;
            $arrData['status'] = 1;
            if (!M('Paper')->save($arrData)) {
                $this->error('操作失败!');
            }
            
            if ($questionAll['type'] == 1) {  //随堂任务
                $this->completeCurriculumAndOpenSpecialty($questionAll['relat_id']);
            }
        }

        $return = array(
            'question_id' => $question_id,
            'check_score' => $data['check_score'],
            'answer' => $questionInfo['answer'],
            's_answer' => $s_answer,
            'total_score' => $total_score,
            'star_num' => $this->_starNum($total_score)
        );

        $this->returnList($return);
    }

    /**
     * 完成课程并递增开启专业模块
     * 1.如果课时是课程中的最后一节，随堂任务通过，完成课程
     * 2.如果所有课程已完成，完成专业且开启下一专业
     * @param int $iPeriodId 课时ID
     */
    protected function completeCurriculumAndOpenSpecialty($iPeriodId) {
        //查询所属课程
        $iUserId = $this->iUserId;
        $iCurriculumId = M('Period')->where(array('period_id' => $iPeriodId))->getField('curriculum_id');
        $arrPeriod = M()->table('qy_period p')
                ->field('
                        p.period_id,p.period_name,p.video_duration,p.chapter_id,
                        MAX(pp.total_score) as max_total_score
                ')
                ->join('LEFT JOIN qy_paper AS pp ON pp.relat_id = p.period_id AND pp.type = 1 AND pp.status = 1 AND pp.user_id = ' . $iUserId)
                ->where(array('p.curriculum_id' => $iCurriculumId, 'p.status' => 1))
                ->group('p.period_id')
                ->order('p.chapter_id ASC,p.sort ASC')
                ->select();
        if (empty($arrPeriod)) {
            return FALSE;
        }

        $is_all_pass = 1;   //课程下的所有课时随堂任务是否全部通过 0-未通过 1-已通过
        foreach ($arrPeriod as $val) {
            if (empty($val['max_total_score']) || 80 > $val['max_total_score']) {
                $is_all_pass = 0;
            }
        }
        if ($is_all_pass == 0) {
            return FALSE;
        }
        
        $objOpenLock = new \Common\Model\OpenLockModel();
        //如果该课程已通过，qy_open_lock记录该课程已完成
        $objOpenLock->completeCurriculum($iUserId, $iCurriculumId);
        //查看专业下课程是否全部通过，如果通过，开启下一个专业
        $iSpecialtyId = M('Curriculum')->where(array('curriculum_id' => $iCurriculumId))->getField('specialty_id');
        $arrOpenLock = M()->table('qy_curriculum c')->field('c.curriculum_id, pl.status')
                ->join('LEFT JOIN qy_open_lock AS pl ON pl.relat_id = c.curriculum_id AND pl.type = 2 AND pl.status = 2 AND pl.user_id = ' . $iUserId)
                ->where(array('c.status' => 1,'c.specialty_id'=>$iSpecialtyId))
                ->select();
        
        $is_all_complete = 1;   //是否全部 0-否 1-是
        foreach ($arrOpenLock as $val) {
            if ($val['status'] != 2) {
                $is_all_complete = 0;
            }
        }
        if (empty($is_all_complete)) {
            return FALSE;
        }
        
        //完成本专业，开启下一专业
        $objOpenLock->openOrCompleteSpecialty($iUserId, $iSpecialtyId, 2);

        //查询一下专业
        $objSpecialty = M('Specialty');
        $currentSpecialtyInfo = $objSpecialty->where(array('specialty_id' => $iSpecialtyId, 'status' => 1))->find();
        $nextSpecialtyInfo = $objSpecialty->field('specialty_id')->where(array('sort' => $currentSpecialtyInfo['sort'] + 1, 'cate_id' => $currentSpecialtyInfo['cate_id'], 'status' => 1))->order('sort DESC')->limit(1)->find();
        if (!empty($nextSpecialtyInfo)) {
            //开启下一专业
            $objOpenLock->openOrCompleteSpecialty($iUserId, $nextSpecialtyInfo['specialty_id'], 1);
        }
    }

}
